package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/3 15:43
 */
public class J58 {

    /** https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/ */
    public static String reverseWords(String s) {
        // 暴力解, 分割成数组, 反转数组在拼接
        String[] s1 = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = s1.length-1; i >= 0; i--) {
            if(!s1[i].equals("")) {
                sb.append(s1[i]+" ");
            }
        }
        return sb.toString().trim();
    }
    public static String reverseWords2(String s) {
        // 双指针, 从右往左搜索 i~j.为一个单词
        StringBuilder sb = new StringBuilder();
        s = s.trim();
        int l = s.length()-1, r = l;
        while (l >= 0) {
            while (l >= 0 && s.charAt(l) != ' ') {
                l--;
            }
            sb.append(s.substring(l+1, r+1) + " ");
            while (l >= 0 && s.charAt(l) == ' ') {
                l--;
            }
            r = l;
        }
        return sb.toString().trim();
    }

    /** https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/ */
    public static String reverseLeftWords(String s, int n) {
        if(s== null || s.length() < n) {
            return s;
        }
        return s.substring(n) + s.substring(0, n);
    }


    // for test
    public static void main(String[] args) {
//        String s = "the sky      is blue.";
//        System.out.println(reverseWords(s));
//        System.out.println(reverseWords2(s));


        String s = "abcdefg";
        System.out.println(reverseLeftWords(s, 2));
    }

}
